#ifndef __TCP_SERVE_H__
#define __TCP_SERVE_H__

#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<string>
#include<cstdlib>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>

class tcpClient{
private:
    std::string ser_ip;
    int ser_port;
    int sock;
public:
    tcpClient(std::string ip,int port):ser_ip(ip),ser_port(port){
        
    }
    void initClient(){
        sock = socket(AF_INET,SOCK_STREAM,0);
        if(sock < 0){
            std::cerr<<" socket error "<<std::endl;
            exit(1);
        }
        struct sockaddr_in end_point;
        end_point.sin_addr.s_addr = inet_addr(ser_ip.c_str());
        end_point.sin_family = AF_INET;
        end_point.sin_port =htons(ser_port);
        //连接的同时自动绑定
        if(connect(sock,(struct sockaddr*)&end_point,sizeof(end_point))!=0){
            std::cerr<<"connect error"<<std::endl;
        }
        //connect success;
    }
    void start(){
        std::cout<<"Please Enter Msg#";
        fflush(stdout);
        char msg[128];
        //while(true){
            ssize_t s = read(0,msg,sizeof(msg)-1);
            if(s > 0){
                msg[s-1] = 0;
                //发送数据
                send(sock,msg,strlen(msg),0);
                //读取数据
                ssize_t ss = recv(sock,msg,sizeof(msg)-1,0);
                if(ss > 0){
                    msg[ss] = 0;
                    std::cout<<"Server echo # "<<msg<<std::endl;
                }
                //if(ss == 0){
                //    break;
                //}
            }
        //}
    }
    ~tcpClient(){
        close(sock);
    }
};
#endif
